export const capitalizeFirstLetter = (string: string) => {
    return string.charAt(0).toUpperCase() + string.slice(1);
};

export const stripHtml = (html: string, length: number = 300, ellipsis: boolean = true) => {
    // 移除 HTML 标签
    let text = html.replace(/<[^>]*>/g, '');
    // 移除换行符和多余的空白字符
    text = text.replace(/\s+/g, ' ').trim();
    let truncatedText = text.substring(0, length);
    if (text.length > length && ellipsis) {
        const ellipsisLength = '...'.length;
        truncatedText = truncatedText.substring(0, truncatedText.length - ellipsisLength) + '...';
    }
    return truncatedText;
};

export const abbreviateNameWithStar = (name: string) => {
    // 检查输入的名字是否为空
    if (!name) {
        return "";
    }

    // 获取第一个字母并转换为大写
    const firstLetter = name.charAt(0).toUpperCase();

    // 使用正则表达式替换除了第一个字母外的所有字符为星号
    return firstLetter + name.slice(1).replace(/[^ ]/g, '*');
};

export const formatNumber = (number: number | null) => {
    if (number == null) {
        return '0';
    }

    // 添加千分符的函数
    const addThousandsSeparator = (num: number) => {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };

    if (number >= 1000000) {
        return (number / 1000000).toFixed(1) + 'M'; // 百万
    } else if (number >= 1000) {
        return (number / 1000).toFixed(1) + 'K'; // 千
    } else {
        return addThousandsSeparator(number); // 小于1000的数字直接返回，带千分符
    }
};

export const hideMobile = (number: string) => {
    return number.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

export const timeAgo = (inputDate: string) => {
    // inputDate = new Date(inputDate).toString()
    let date;
     // 替换掉可能导致问题的字符
    inputDate = inputDate.replace(/-/g, "/").replace(/T|Z/g, " ");
    date = new Date(inputDate.trim());

    const now = new Date();
    const diff = now.getTime() - date.getTime(); // 时间差，单位为毫秒

    // 如果日期无效，返回空字符串或其他提示
    if (isNaN(diff)) {
        return "无效日期";
    }

    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const months = Math.floor(days / 30);
    const years = Math.floor(days / 365);

    if (seconds < 60) {
        return "刚刚";
    } else if (minutes < 60) {
        return minutes + "分钟前";
    } else if (hours < 24) {
        return hours + "小时前";
    } else if (days < 30) {
        return days + "天前";
    } else if (months < 12) {
        return months + "个月前";
    } else {
        return years + "年前";
    }
}